package com.zh.simple.common;

import java.util.Optional;

/**
 * Http请求返回的对象
 */
public final class ApiResult<T> {
    static final int OK_CODE = 0;
    static final int DEFAULT_FAIL_CODE = 100000;
    /**
     * 请求ID
     * 每个请求都有一个唯一标识，用于追踪请求
     */
    private String aid;

    /**
     * 返回码
     */
    private int code;
    /**
     * 返回提示消息
     * 用于前端提示
     */
    private String msg;
    /**
     * 返回错误信息
     * 用于排查问题
     */
    private String error;

    /**
     * 返回数据
     */
    private T data;

    private ApiResult() {
    }

    private ApiResult(int code, T data, String msg) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public static ApiResult<Void> success() {
        return new ApiResult<>(OK_CODE, null, "");
    }

    public static <T> ApiResult<T> success(T data) {
        return new ApiResult<>(OK_CODE, data, "");
    }

    public static <T> ApiResult<T> success(T data, String msg) {
        return new ApiResult<>(OK_CODE, data, msg);
    }

    public static <T> ApiResult<T> fail(String msg) {
        return new ApiResult<>(DEFAULT_FAIL_CODE, null, msg);
    }

    public static <T> ApiResult<T> fail(int code, String msg) {
        return new ApiResult<>(code == OK_CODE ? DEFAULT_FAIL_CODE : code, null, msg);
    }

    public String getAid() {
        return aid;
    }

    public void setAid(String id) {
        if (this.aid == null)
            this.aid = id;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        if (this.code == 0)
            this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        if (this.msg == null)
            this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        if (this.data == null)
            this.data = data;
    }

    public String getError() {
        return isOk() ? null : Optional.ofNullable(error).orElse(msg);
    }

    public ApiResult<T> setError(String error) {
        if (isOk() && error != null) throw new IllegalArgumentException("OK时，不能set error信息");

        if (this.error == null)
            this.error = error;
        return this;
    }

    public boolean isOk() {
        return code == OK_CODE;
    }

    @Override
    public String toString() {
        return "ApiResult{" +
                "aid='" + aid + '\'' +
                ", code=" + code +
                ", msg='" + msg + '\'' +
                ", error='" + error + '\'' +
                ", data=" + data +
                '}';
    }
}
